package com.whzykj.ctrl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.whzykj.common.DateUtil;

public class UploadController extends Controller{
	public void imageUpload() {
		try {
			System.out.println("上传文件...");
//			UploadFile uploadFile = getFile("imageFile", PathKit.getWebRootPath()
//					+ "/temp", 20 * 1024 * 1024, "utf-8");
			UploadFile upFile = getFile("img", "temp/");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} // 最大上传20M的图片
		// 异步上传时，无法通过uploadFile.getFileName()获取文件名
		String fileName = getPara("fileName");
		fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); // 去掉路径

		// 异步上传时，无法通过File source = uploadFile.getFile();获取文件
		File source = new File(PathKit.getWebRootPath() + "/upload/temp/" + fileName); // 获取临时文件对象

		String extension = fileName.substring(fileName.lastIndexOf("."));
		String savePath = PathKit.getWebRootPath() + "/upload/images/"
				+ DateUtil.getCurrentDate();
		JSONObject json = new JSONObject();

		if (".png".equals(extension) || ".jpg".equals(extension)
				|| ".gif".equals(extension) || "jpeg".equals(extension)
				|| "bmp".equals(extension)) {
			fileName = DateUtil.getCurrentTime() + extension;

			try {
				FileInputStream fis = new FileInputStream(source);

				File targetDir = new File(savePath);
				if (!targetDir.exists()) {
					targetDir.mkdirs();
				}

				File target = new File(targetDir, fileName);
				if (!target.exists()) {
					target.createNewFile();
				}

				FileOutputStream fos = new FileOutputStream(target);
				byte[] bts = new byte[1024 * 20];
				while (fis.read(bts, 0, 1024 * 20) != -1) {
					fos.write(bts, 0, 1024 * 20);
				}

				fos.close();
				fis.close();
				json.put("error", 0);
				json.put("src", "upload/images/" + DateUtil.getCurrentDate()
						+ "/" + fileName); // 相对地址，显示图片用
				source.delete();

			} catch (FileNotFoundException e) {
				json.put("error", 1);
				json.put("message", "上传出现错误，请稍后再上传");
			} catch (IOException e) {
				json.put("error", 1);
				json.put("message", "文件写入服务器出现错误，请稍后再上传");
			}
		} else {
			source.delete();
			json.put("error", 1);
			json.put("message", "只允许上传png,jpg,jpeg,gif,bmp类型的图片文件");
		}

		renderJson(json.toJSONString());
	}
}
